import re
from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django.http import JsonResponse
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generic_openid_tocken, check_openid_tocken
from apps.users.models import User
from meiduo_mall import settings
from utils.response_code import RETCODE
import logging
logger = logging.getLogger('django')



"""提供QQ登录页面网址
https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
"""
class OauthQQURLView(View):

    def get(self,request):

        state =request.GET.get('next')
        qq= OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI,
            client_secret=settings.QQ_CLIENT_SECRET,
            state=state
        )

        login_url = qq.get_qq_url()



        # login_url = 'https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type%20=code&client_id=101518219&redirect_uri=http://www.meiduo.site:8000/oauth_callback&state=test'


        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_url})





class OauthQQUserView(View):
    def get(self,request):

        code =request.GET.get('code')
        if code is None:
            return http.HttpResponseBadRequest('参数有误')

        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI,
            client_secret=settings.QQ_CLIENT_SECRET,

        )


        token = qq.get_access_token(code)

        openid = qq.get_open_id(token)
        try:
            qquser=OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            openid_tocken = generic_openid_tocken(openid)

            return render(request, 'oauth_callback.html',context={'openid':openid_tocken})


        else:
            user=qquser.user

            login(request,user)
            next = request.GET.get('state')

            if next:
                response = redirect(next)

            else:

                response = redirect(reverse('contents:index'))

                response.set_cookie('username',user.username,max_age=14*24*3600)

            return response


    def post(self,request):

        data = request.POST
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code_client = data.get('sms_code')
        access_token = data.get('access_token')

        if not all([mobile,password,sms_code_client,access_token]):



            return http.HttpResponseBadRequest('参数不全')


        if not re.match(r'^1[3-9]\d{9}$',mobile):


            return http.HttpResponseBadRequest('手机号不满足条件')

        if not re.match(r'^[0-9a-zA-Z_-]{8,20}$', password):
            return http.HttpResponseBadRequest('密码格式不对')


        redis_conn = get_redis_connection('code')

        sms_code_server = redis_conn.get('sms_%s'%mobile)
        if not sms_code_server:
            return http.HttpResponseBadRequest('短信验证码已过期')
        if sms_code_server.decode() != sms_code_client:
            return http.HttpResponseBadRequest('短信验证码不一致')

        openid=check_openid_tocken(access_token)

        if openid is None:
            return http.HttpResponseBadRequest('openid错误')

        try:
            user = User.objects.get(mobile=mobile)

        except User.DoesNotExist:

            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile

            )

        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest('密码错误')

        try:
            OAuthQQUser.objects.create(
                openid=openid,
                user=user

            )
        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest('数据库错误')


        login(request,user)
        next = request.GET.get('next')

        if next:
            response = redirect(next)

        else:

            response = redirect(reverse('contents:index'))

            response.set_cookie('username',user.username,max_age=14*24*3600)

        return response
